package com.java.thread;

/**
 * 测试两个线程共享一个数组资源MyArrayList
 * @author jack
 *
 */
public class TestThreadSharedResource {

	public static void main(String[] args) {
		MyArrayList arr=new MyArrayList();
		Thread t1=new ThreadArrayA(arr);
		Thread t2=new ThreadArrayB(arr);
		t1.start();
		t2.start();
		
		try {
			Thread.sleep(5000);//主线程睡眠，让另两个线程先执行完
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(arr.toString());
	}

}


class ThreadArrayA extends Thread {
	private MyArrayList arr;
	public ThreadArrayA(MyArrayList arr){
		this.arr=arr;
	}
	public void run(){
		arr.add("hello");
		arr.add("hehe");
		arr.add("xixi");
	}
}
class ThreadArrayB extends Thread{
	private MyArrayList arr;
	public ThreadArrayB(MyArrayList arr){
		this.arr=arr;
	}
	public void run(){
		arr.add("HELLO");
		arr.add("HEHE");
		arr.add("XIXI");
	}
}


class MyArrayList {
	private Object[] data;
	private int count;
	public MyArrayList() {
		super();
		this.data = new Object[10];
		this.count = 0;
	}
	public synchronized void add(Object obj){
		data[count]=obj;
		for(int i=0;i<1000000;i++){
			;
		}
		count++;
	}
	public String toString(){
		StringBuffer str=new StringBuffer();
		str.append("[");
		for(int i=0;i<count;i++){
			str.append(data[i]);
			if(i<count-1){
				str.append(",");
			}
		}
		str.append("]");
		return str+"";
	}
	
}